#!/usr/bin/python2.6
#
# Copyright 2011 Eric Gavaletz <gavaletz@gmail.com>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__author__ = 'Eric Gavaletz <gavaletz@gmail.com>'
__credits__ = 'None'
__date__ = '22 February 2011'
__version__ = '$Revision: 1 $'

import sys
import re
import shelve
import FirstHack

def scan(pfile, back_file):
    """
    #title - str
    #cost - int
    #value - int
    #desc - str
    #solution_format - str
    #solution - ?
    ########################
    World's Hardest Easy Geometry Problem
    1000
    2000
    Using only elementary geometry, determine angle x.
    int
    30
    """
    f = open(pfile, "r")
    pl = FirstHack.Problem_list(back_file)
    lines = list()
    for l in f:
        if not l.startswith("#"):
            lines.append(l.strip())

    while len(lines):
        title = lines.pop(0)
        cost = int(lines.pop(0))
        payoff = int(lines.pop(0))
        desc = lines.pop(0)
        solution_format = lines.pop(0)
        solution = None
        if solution_format == "int":
            solution = int(lines.pop(0))
        elif solution_format == "float":
            solution = float(lines.pop(0))
        else:
            solution = lines.pop(0)

        p = FirstHack.Problem(title, cost, payoff, desc, solution_format, solution)
        pl.append(p)

    return pl

def verify_and_write(plist):
    """
    Ask before we clobber someone's file...its called being polite.
    """
    print plist.list_all()
    print "\nThere are %d problems ready to be writen to %s\n" % (len(plist.p_list),
            plist.backing_file)
    ok = raw_input("Is this OK? y/n:")
    if ok == "y":
        plist.write()
    else:
        print "ABORTING"

def usage():
    """
    Helping n00bs since day one...
    """
    print "Use the source luke..."
    print "python %s <problem_file> -o <backing_file.prob>" % sys.argv[0]
    print "backing_file.prob must end with \".prob\""
    sys.exit()


def main():
    """
    This is where we start :-)
    """
    if len(sys.argv) < 4:
        usage()
    if sys.argv[2] != "-o":
        usage()
    if not sys.argv[3].endswith(".prob"):
        usage()

    pfile = sys.argv[1]
    back_file = sys.argv[3]

    plist = scan(pfile, back_file)
    verify_and_write(plist)

if __name__ == "__main__":
    main()
